<?php
/**
 * Galan Tour Management System.
 * Author: Enkuso (eegii2you@yahoo.com)
 * Date: 11/6/12
 */
class sfWidgetFormTagsInput extends sfWidgetFormDoctrineChoice
{
    protected function configure($options = array(), $attributes = array())
    {
        parent::configure($options, $attributes);

        $this->setAttribute('class', 'tagsinput');
        $this->setOption('multiple', true);
        $this->setAttribute('data-provide','typeahead');
    }

    public function render($name, $value = null, $attributes = array(), $errors = array())
    {
        $this->setAttribute('data-source',$this->getDataSource());
        $value = is_array($value) ? implode(',',$this->getSelectedChoices($value)) : $value;
        return $this->renderTag('input', array_merge(array('type' => $this->getOption('type'), 'name' => $name, 'value' => $value), $attributes));
    }

    public function getStylesheets()
    {
        return array(
            "/css/plugins/jquery.tagsinput.css" => 'screen'
        );
    }
    public function getJavaScripts()
    {
        return array(
            "/js/plugins/tagsInput/jquery.tagsinput.min.js",
            "/js/plugins/tagsInput/sfWidgetFormTagsInput.js",
        );
    }
    public function getSelectedChoices($values)
    {
        if(!is_array($values))
            $values = array($values);
        $choices = $this->getChoices();

        return array_intersect_key($choices,array_flip($values));
    }

    public function getDataSource()
    {
        $choices = $this->getChoices();

        $result = '[';
        foreach($choices as $choice)
            $result .= '"'.$choice.'",';

        if(count($choices))
            $result = substr_replace($result, "", -1);

        $result .= ']';

        return $result;
    }
}
